package org.springframework.web.servlet.ajax.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class keeps track of commands a developer has given, presumably from a
 * Controller, to write JSON. A developer can store JavaScript strings, 
 * CHUCK TODO
 * 
 * JSON commands are stored, rather than acted up immediately, because it's
 * premature to write a JSON response in the Controller. One issue is that
 * Spring MVC has not yet stored the appropriate Errors object in the Request,
 * and this will prevent the RequestContext from using PropertyEditors that have
 * been registered on a DataBinder. One way this problem manifests itself is
 * that dates will not be presented correctly in a form even though a
 * CustomDateEditor has been registered on the application's DataBinder.
 * 
 * @author Charles Tassoni
 */

//CHUCK TODO
//Need to allow a callback class to be passed in that JsonAjaxReaction lets see
//the map just before it's made into JSON.  One use:  Turn several partials that lie
//on a map into one large partial that can then be inserted into a single div.
public class JsonAjaxImpl implements JsonAjax {

	List<String> javaScriptViews = new ArrayList<String>();
	List<String> javaScriptStrings = new ArrayList<String>();
	List<List<String>> keysAndViewNamesForRendering = new ArrayList<List<String>>();
	List<List> addedToJsonMap =  new ArrayList<List>();
	
	List<List> keepsTrackOfOthers = new ArrayList<List>();
	
	public void addJavascript(String javascript){
		javaScriptStrings.add(javascript);
		
		keepTrack(javaScriptStrings, JAVASCRIPT_VIA_STRING);
	}
	
	public void addJavascriptView(String viewName){		
		javaScriptViews.add(viewName);
		
		keepTrack(javaScriptViews, JAVASCRIPT_VIA_VIEW);
	}
	
	public void addPartial(String jsonKey, String viewName){
		addPartial(jsonKey, viewName, new HashMap());
	}
	
	/**
	 * Chuck TODO document, probably in itnerface, but especially  modelOverride 
	 */
	public void addPartial(String jsonKey, String viewName, Map modelOverride){
		List list  = new ArrayList(3);
		list.add(jsonKey);
		list.add(viewName);
		list.add(modelOverride);
		keysAndViewNamesForRendering.add(list);
		
		keepTrack(keysAndViewNamesForRendering, RENDER_A_PARTIAL);		
		
	}
	
	public void addToJsonMap(Object key, Object value){
		List keyAndValueForJsonMap  = new ArrayList(2);
		keyAndValueForJsonMap.add(key);
		keyAndValueForJsonMap.add(value);
		addedToJsonMap.add(keyAndValueForJsonMap);
		
		keepTrack(addedToJsonMap, AD_HOC_ADDITION);
	}	
	
	private void keepTrack(List list, Short command){
		List trackingInfo = new ArrayList(3);
		trackingInfo.add(command);
		trackingInfo.add(list);
		trackingInfo.add(list.size() - 1);
		
		keepsTrackOfOthers.add(trackingInfo);
	}	
	

	public List<List >getAllJsonWork(){
		return this.keepsTrackOfOthers;
	}
	

}
